import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { CommonDialog } from '../../../components/common/Dialog';
import { ItemCpt } from '../claimApplication/_components/ItemCpt';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const TAB_LIST = [
	{
		name: '跟进中',
		status: 'AUTH_WAIT',
		count: 0,
	},
	{
		name: '已拒绝',
		status: 'AUTH_UNPASS',
		count: 0,
	},
	{
		name: '已认证',
		status: 'AUTH_PASS',
		count: 0,
	},
	{
		name: '历史会员',
		status: 'HISTORY',
		count: 0,
	}
]


export class claimRecord extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '用户认证记录',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('CrMtManage') }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props)
		let { tabIndex } = props.navigation.state.params || {};
		this.tabIndex = tabIndex || 0;
		this.state = {
			status: 'data',
			listData: [],
			refreshIcon: false, // 下拉刷新图标
			count: [],
			alertShow: false,
			options: [],
			choice: '',
			totalPage:0
		};
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.pageParams = { // TODO
			companyName: '',
			mobile: '',
			recordStatus: TAB_LIST[this.tabIndex].status
		};
		this.historyParams ={
			memMobile:'',
			entName:'',
			pageNo:1,
			pageSize: 10
		}
		this.searchKey = '';
		this.roles;
		this.userId = '';
	}

	async componentWillMount () {
		this.initPage();
	}
	async componentWillReceiveProps (nextProps) {
		if (nextProps.navigation.state.params.tabIndex) {
			this.tabIndex = nextProps.navigation.state.params.tabIndex;
		}
		this.initPage();
	}

	async initPage () {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		console.log(userInfo)
		this.userId = userInfo.userId
		if (userInfo.isBizer === '1') {
			this.roles = 'salesman'
		}
		userInfo.userRoles.map((item) => {
			if (item.roleCode === 'ROLE_APP_BUS_OPERATION') {
				this.roles = 'operation'
			}
			if (item.roleCode === 'ROLE_APP_ORDER_ORGAN_QUERY') {
				this.roles = 'leader'
			}
		})
		console.log(this.roles)
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload,
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
		this.pageParams ={
			recordStatus:TAB_LIST[this.tabIndex].status,
			companyName:this.searchKey,
			mobile:this.searchKey,
			corpId:this.state.choice.corpId
		}
		this.historyParams.memMobile = this.searchKey
		this.historyParams.entName = this.searchKey
		this.historyParams.corpId = this.state.choice.corpId
		let res
		if(this.tabIndex=== 3){
			res = await HTTP.POST(API_GENERATE(API.ENTERPRICE_MEMBER), this.historyParams);
			let {recordWaitCount, recordUnpassCount, recordPassCount,recordHistoryCount} = res
			res = res.paginationModel
			if (res) {
				this.setState({
					status: res.rows.length > 0 ? 'data' : 'empty',
					listData: this.historyParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
					refreshIcon: false,
					count: [recordWaitCount,recordUnpassCount, recordPassCount,recordHistoryCount],
					totalPage: res.totalPage,
				})
			} else {
				this.setState({
					refreshIcon: false,
					status: 'error',
					count: ['0', '0', '0', '0']
				})
			}
		}
		else{
			if (this.roles === 'salesman') {
				res = await HTTP.POST(API_GENERATE(API.ENTERPRISE_APPLY_LIST), this.pageParams);
				}
				//是否为领导
				else {
					res = await HTTP.POST(API_GENERATE(API.ENTERPRISE_APPLY_LIST_LEADER), this.pageParams);
				}
				if (res) {
					this.setState({
						status: res.applyRecordListList.length > 0 ? 'data' : 'empty',
						listData: res.applyRecordListList,
						refreshIcon: false,
						count: [res.recordWaitCount, res.recordUnpassCount, res.recordPassCount,res.recordHistoryCount]
					})
				} else {
					this.setState({
						refreshIcon: false,
						status: 'error',
						count: ['0', '0', '0', '0']
					})
				}
		}
		
	}

	loadMore = () => {
		if (this.tabIndex===3&&this.state.totalPage > this.historyParams.pageNo) {
		  this.historyParams.pageNo++;
		  this.reload = false;
		  this.initPage();
		}
	  }
	// 刷新页面
	reloadPage () {
		if(this.tabIndex===3){
			this.historyParams.pageNo = 1;
		}
		this.reload = true;
		this.initPage();
	}

	_onErrorRefresh = () => {
		this.initPage();
	}

	changeTab (index) {
		if (this.tabIndex === index) return;
		this.historyParams.pageNo = 1
		this.tabIndex = index;
		// this.searchKey = ''
		this.reloadPage();
	}
	// 搜索View
	_renderFilterWrap () {
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入企业名称/手机号"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.searchKey}
						onChangeText={(txt) => { this.searchKey = txt; }}
						onSubmitEditing={() => { this.reloadPage(); }}
					/>
				</View>
			</View>
		)
	}
	//tab View
	_renderTabWrap () {
		const { count } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						return (
							index!==3||this.roles==='operation'?
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
								<Text style={[styles.tabText, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text>
								<Text style={[styles.tabText, styles.tabCount, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{count[index]}</Text>
							</TouchableOpacity>
							:null
						)
					})
				}
			</View>
		)
	}


	//跳详情
	_details = (sendData) => {

	}

	_renderListItem = (data) => {
		return (
			<ItemCpt data={data.item} userId={this.userId} roles={this.roles} entrance='record' history={this.tabIndex===3?true:false} />
		)
	}

	render () {
		let { status, listData, refreshIcon, alertShow, options, choice } = this.state;
		return (
			<View style={styles.container}>
				{options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
				{this._renderFilterWrap()}
				{this._renderTabWrap()}
				{/* <Text onPress={() => { navigationSeevice.navigate('recordDetail') }}>detail</Text> */}
				{
					status == 'data' ? (<View style={{ flex: 1 }}>
						<FlatList
							data={listData}
							renderItem={this._renderListItem}
							refreshing={refreshIcon}
							onRefresh={() => { this.reloadPage() }}
							onEndReachedThreshold={1}
                			onEndReached={() => { this.loadMore() }}
						/>
					</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this._onErrorRefresh} />) : null
				}
				<SlideSelect
					alertShow={alertShow}
					options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this.reloadPage();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
		paddingBottom: 30 * scale
	},
	filterWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 270 * scale,
		paddingLeft: 80 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 20 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 40 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'flex-start',
		paddingLeft: 18 * scale,
		paddingRight: 18 * scale,
	},
	tabText: {
		color: '#fff',
		textAlign: 'center'
	},
	tabCount: {
		marginTop: 4 * scale
	},
	tabItem: {
		paddingTop: 14 * scale,
		paddingBottom: 12 * scale,
	},
	listItem: {
		backgroundColor: '#fff',
		borderRadius: 4 * scale,
		marginBottom: 22 * scale
	},
	userInfo: {
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale,
		paddingBottom: 6 * scale,
		paddingTop: 8 * scale,
		borderStyle: 'solid',
		borderTopColor: '#E3E7F0',
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
	},
	warningItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 13 * scale
	},
	userName: {
		fontSize: 12 * scale,
		marginBottom: 4 * scale,
		opacity: .8
	},
	tabTextWho: {
		paddingTop: 14 * scale
	}
})